package com.alibaba.manager;

import com.alibaba.common.SystemConstants;
import com.alibaba.define.domain.ArticleDO;
import com.alibaba.mapper.ArticleMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author : hanyang
 * @date : 2023-11-01 23:00
 **/

@Component
public class ArticleManager {

    @Resource
    ArticleMapper articleDAO;

    /**
     * 分页查询已发布未删除的文章
     */
    public List<ArticleDO> getEfficientArticleByPagination(Integer pageNum, Integer pageSize, Long categoryId) {
        HashMap<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("delFlag", SystemConstants.UN_DELETED);
        parameterMap.put("status", "0");
        parameterMap.put("offset", (--pageNum) * pageSize);
        parameterMap.put("size", pageSize);
        parameterMap.put("categoryId", categoryId);
        return articleDAO.articleList(parameterMap);
    }

    /**
     * 根据id查询文章
     */
    public ArticleDO queryArticleById(Long id) {
        HashMap<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("delFlag", SystemConstants.UN_DELETED);
        parameterMap.put("status", "0");
        parameterMap.put("id", id);
        return Optional.ofNullable(articleDAO.select(parameterMap))
                .filter(list -> !list.isEmpty())
                .map(list -> list.get(0))
                .orElse(null);
    }

    public Integer queryArticleCountByCondition(Long categoryId) {
        HashMap<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("delFlag", SystemConstants.UN_DELETED);
        parameterMap.put("status", "0");
        parameterMap.put("categoryId", categoryId);
        return articleDAO.count(parameterMap);
    }

    /**
     * 查询文章浏览量
     */
    public List<ArticleDO> queryArticleIdAndViewCountList() {
        return articleDAO.queryIdAndViewCountList(SystemConstants.ARTICLE_STATUS_NORMAL, SystemConstants.UN_DELETED);
    }

    /**
     * 批量更新文章阅读量
     */
    public Boolean batchUpdateViewCount(List<ArticleDO> articleDOS) {
        Integer count = articleDAO.batchUpdateViewCount(articleDOS);
        return Objects.equals(1, count);
    }
}
